<template lang="pug">
  el-drawer.commonDrawer(
    title="添加合同"
    :visible="visibleDialog"
    append-to-body
    direction="rtl"
    size="760px"
    destroy-on-close
    @close="$_handleCancel"
  )
    .drawer-content
      form-box(
        ref="form"
        :fields="fields"
        :showBtns="false"
        :layoutCol="{ xs: 12, md: 12, lg: 12 }"
      )
        el-button(slot="form-product" type="primary" icon="el-icon-circle-plus" round @click="productVisible = true") 添加产品
      s-table(
        ref="productTable"
        :column="productColumn2"
        v-if="productRecords.length > 0"
        :dataPops="productRecords"
      )
        template(slot="count" slot-scope="text, scope")
          el-input-number.w(:value="text" controls-position="right" :min="1" @change="val => productFormChange(val, scope.id, 'count')")
        template(slot="discountAmount" slot-scope="text, scope")
          el-input-number.w(:value="text" controls-position="right" :min="1" @change="val => productFormChange(val, scope.id, 'discountAmount')")
        template(slot="amount" slot-scope="text, scope")
          p {{scope.discountAmount * (scope.count || 1)}}
          small.c_warning 折扣：{{scope.discountAmount | toPercent(scope.standardAmount)}}
        template(slot="remark" slot-scope="text, scope")
          el-input.w(:value="text" controls-position="right" @input="val => productFormChange(val, scope.id, 'remark')")
        template(slot="action" slot-scope="text, scope")
          el-link(@click="deleteProductHandle(scope.id)" type="primary") 删除
      el-divider
      alert(type="info" v-if="productRecords.length > 0")
        p
          | 标准价格合计:
          span(v-for="(item, index) in productRecords" :key="item.id")
            small ￥
            | {{item.standardAmount | toThousandFilter}} * {{item.count}}
            span.ml5.mr5(v-if="index !== productRecords.length - 1") +
          span.ml5.mr5 =
          | {{standardAmount | toThousandFilter}}
        p
          | 实际销售合计:
          span(v-for="(item, index) in productRecords" :key="item.id")
            small ￥
            | {{item.discountAmount | toThousandFilter}} * {{item.count}}
            span.ml5.mr5(v-if="index !== productRecords.length - 1") +
          span.ml5.mr5 =
          | {{discountAmount | toThousandFilter}}
        p
          | 合同金额合计:
          span.f18.c_error
            small ￥
            | {{discountAmount | toThousandFilter}}
          el-tag.ml5.vm(type="warning" size="mini") 折扣: {{discountAmount | toPercent(standardAmount)}}
      form-box.mt16(
        ref="otherForm"
        :fields="otherFields"
        :showBtns="false"
        :layoutCol="{ xs: 12, md: 12, lg: 12 }"
      )
    .drawer-footer.tr
      el-button.gradientVertical(size="large" round :loading="submitting" @click="sureHandle") 确定
    el-dialog(
      title="产品选择"
      append-to-body
      center
      destroy-on-close
      :visible="productVisible"
      @close="productVisible = false"
    )
      s-table(
        ref="productTable"
        :dataPops="products"
        :column="productColumn1"
        :selection="true"
        :queryPropsParams="{isVisible: 1}"
        @selection-change="rows => selectProductRows = rows"
      )
      p.tr
        el-button(size="small" type="primary" @click="productSureHandle") 确定
    el-dialog(
      title="合同预览"
      append-to-body
      center
      destroy-on-close
      :visible="contractConfirmObj.visible"
      @close="contractConfirmObj.visible = false"
    )
      #printBox
        alert(type="info")
          h3
            | 合同金额合计:
            span.f18.c_error
              small ￥
              | {{discountAmount | toThousandFilter}}
            el-tag.ml5.vm(type="warning" size="mini") 折扣: {{discountAmount | toPercent(standardAmount)}}
          p 宝宝姓名：{{contractConfirmObj.data.childName}}
          p 签约时间：{{contractConfirmObj.data.signDate}}
          p 合同时间：{{contractConfirmObj.data.beginDate}} ~ {{contractConfirmObj.data.endDate}}
        s-table(
          ref="productTable"
          :column="productColumn3"
          :dataPops="productRecords"
        )
          template(slot="amount" slot-scope="text, scope")
            p {{scope.discountAmount * (scope.count || 1)}}
            small.c_warning 折扣：{{scope.discountAmount | toPercent(scope.standardAmount)}}
        el-row(:gutter="24")
          el-col(:span="24")
            p 付款方式：{{dictFilter(contractConfirmObj.data.payChannel, 'payChannel', 'id', 'name')}}
          el-col(:span="24")
            p 备注：{{contractConfirmObj.data.remark}}
      p.tr
        el-button(size="small" @click="printHandle") 打印合同
        el-button(size="small" type="primary" @click="submitHandle") 确定
</template>
<script>
import { mapGetters } from 'vuex'
import dictMixin from '@/mixins/dict'
import { print } from '@/utils/util'
import Alert from '@/components/Basic/Alert'
import { contractAdd, productList, attachmentAdd, checkContractCode } from '../api'

const productColumn1 = [
  {
    label: '产品名称',
    prop: 'name'
  },
  {
    label: '标准单价',
    prop: 'standardAmount'
  },
  {
    label: '销售单位',
    prop: 'unit'
  }
]

const productColumn2 = [
  {
    label: '产品名称',
    prop: 'name'
  },
  {
    label: '标准单价',
    prop: 'discountAmount',
    width: '146'
  },
  {
    label: '销售单位',
    prop: 'unit'
  },
  {
    label: '意向数量',
    prop: 'count',
    width: '126'
  },
  {
    label: '总价',
    prop: 'amount',
    width: '126'
  },
  {
    label: '备注',
    prop: 'remark',
    width: '126'
  },
  {
    label: '操作',
    prop: 'action'
  }
]

const productColumn3 = [
  {
    label: '产品名称',
    prop: 'name'
  },
  {
    label: '实际售价',
    prop: 'discountAmount',
    width: '146'
  },
  {
    label: '销售单位',
    prop: 'unit'
  },
  {
    label: '购买数量',
    prop: 'count',
    width: '126'
  },
  {
    label: '总价',
    prop: 'amount',
    width: '126'
  },
  {
    label: '备注',
    prop: 'remark',
    width: '126'
  }
]

export default {
  components: {
    Alert
  },
  mixins: [dictMixin],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    info: {
      type: Object,
      default: () => ({})
    },
    id: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      submitting: false,
      formData: {},
      productVisible: false,
      productColumn1, // 产品选择弹窗产品表格列
      productColumn2, // 已选择产品弹窗产品表格列
      productColumn3, // 合同信息确认弹窗产品表格列
      products: [],
      selectProductRows: [], // 弹窗选中
      productRecords: [], // 意向产品
      contractConfirmObj: { // 合同信息确认弹窗
        data: {},
        visible: false
      }
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    visibleDialog: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    // 计算意向产品总金额
    standardAmount () {
      const { productRecords } = this
      return productRecords.reduce((sum, cur) => {
        return sum + (cur.standardAmount || 0) * (cur.count || 1)
      }, 0)
    },
    // 计算意向产品折扣后总金额
    discountAmount () {
      const { productRecords } = this
      return productRecords.reduce((sum, cur) => {
        return sum + (cur.discountAmount || 0) * (cur.count || 1)
      }, 0)
    },
    fields () {
      const { info, formData } = this
      return [
        {
          label: '宝宝姓名',
          key: 'childName',
          type: 'text',
          layoutCol: { xs: 24, md: 24, lg: 24 },
          initialValue: info.childName
        },
        {
          label: '合同标题',
          key: 'name',
          rules: [{ required: true, message: '请输入' }],
          initialValue: formData.name
        },
        {
          label: '合同编号',
          key: 'code',
          initialValue: formData.code,
          rules: [{ required: true, message: '请输入' }],
          events: {
            change: val => this.formChange(val, 'code')
          }
        },
        {
          label: '合同时间',
          key: 'Date',
          type: 'daterange',
          formatFlag: true,
          key1: 'beginDate',
          key2: 'endDate',
          rules: [{ required: true, message: '请输入' }],
          initialValue: formData.birthday
        },
        {
          label: '签约时间',
          key: 'signDate',
          type: 'date',
          formatFlag: true,
          rules: [{ required: true, message: '请输入' }],
          initialValue: formData.signDate
        },
        {
          label: '购买产品',
          key: 'product',
          layoutCol: { xs: 24, md: 24, lg: 24 },
          type: 'slot'
        }
      ]
    },
    otherFields () {
      const { discountAmount, formData } = this
      return [
        {
          label: '付款',
          key: 'payType',
          type: 'radio',
          layoutCol: { xs: 24, md: 24, lg: 24 },
          rules: [{ required: true, message: '请输入' }],
          fieldProps: {
            options: [
              { id: '1', name: '定金' },
              { id: '2', name: '全款' }
            ]
          },
          events: {
            change: val => this.formChange(val, 'payType')
          }
        },
        {
          label: '付款方式',
          key: 'payChannel',
          type: 'select',
          rules: [{ required: true, message: '请输入' }],
          fieldProps: {
            dictKey: 'payChannel'
          }
        },
        {
          label: '实付',
          key: 'practicalAmount',
          type: 'number',
          rules: [{ required: true, message: '请输入' }],
          initialValue: formData.payType === '2' ? discountAmount : 0,
          fieldProps: {
            disabled: formData.payType === '2'
          }
        },
        {
          label: '可延课天数',
          key: 'surplusLeaveDay',
          type: 'number',
          initialValue: 10,
          layoutCol: { xs: 24, md: 24, lg: 24 }
        },
        {
          label: '备注',
          key: 'remark',
          type: 'textarea',
          layoutCol: { xs: 24, md: 24, lg: 24 }
        },
        {
          label: '附件',
          key: 'attachmentUrl',
          type: 'upload',
          layoutCol: { xs: 24, md: 24, lg: 24 }
        }
      ]
    }
  },
  created () {
    this.getProductList()
  },
  methods: {
    // 校验合同编号
    async checkContractCode (contractCode) {
      const { curArea, formData } = this
      const flag = await checkContractCode({ areaId: curArea.areaId, contractCode })
      if (!flag) {
        this.$confirm('合同编号校验不通过?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.formData = {
            ...formData,
            code: ''
          }
        })
      }
    },
    formChange (val, key) {
      if (key === 'code') {
        this.checkContractCode()
      }
      if (key === 'payType') {
        console.log(val)
        this.formData = {
          ...this.formData,
          payType: val
        }
      }
    },
    // 获取产品列表
    getProductList () {
      this.ProductLoading = true
      productList().then(res => {
        this.products = res.content || []
      }).finally(() => {
        this.ProductLoading = false
      })
    },
    // 选择产品
    productSureHandle () {
      this.productRecords = this.selectProductRows.map(x => {
        x.discountAmount = x.standardAmount
        x.count = 1
        return x
      })
      this.productVisible = false
    },
    productFormChange (val, id, key) {
      const { productRecords } = this
      this.productRecords = productRecords.map(x => {
        if (x.id === id) {
          x[key] = val
        }
        return x
      })
    },
    // 删除选中意向产品
    deleteProductHandle (id) {
      const { productRecords } = this
      this.productRecords = productRecords.filter(x => x.id !== id)
    },
    // 打印
    printHandle () {
      print('printBox')
    },
    // 确定
    async sureHandle () {
      const { productRecords } = this
      if (!productRecords?.length) {
        this.$message.error('请选择至少一项产品')
        return
      }
      const values = await this.$refs.form.submitForm()
      const otherValues = await this.$refs.otherForm.submitForm()
      delete values.product
      console.log(values)
      this.contractConfirmObj = {
        data: {
          ...values,
          ...otherValues
        },
        visible: true
      }
    },
    // 合同添加
    async submitHandle () {
      const { id, productRecords, curArea } = this
      const contractConfirmData = this.contractConfirmObj?.data || {}
      const { attachmentUrl, ...params } = contractConfirmData
      const attachments = attachmentUrl.filter(x => !!x.url)
      contractAdd({
        ...params,
        areaId: curArea.areaId,
        attachments: JSON.stringify(attachments),
        clienteleId: id,
        productRecords: JSON.stringify(productRecords.map(x => {
          return {
            productId: x.id,
            count: x.count,
            remark: x.remark || '',
            practicalAmount: x.discountAmount
          }
        }))
      }).then(() => {
        attachmentUrl.map(file => {
          attachmentAdd({ clienteleId: id, name: file.name, attachmentUrl: file.url })
        })
        this.contractConfirmObj.visible = false
        this.$message.success('提交成功')
        this.$emit('getList')
        this.$_handleCancel()
      })
    },
    $_handleCancel () {
      this.visibleDialog = false
    }
  }
}
</script>
